#include "QToupHandler.h"
#include <QThread>
#include <QDebug>
#include <QImage>

//#include "qnetworktoup.h"


#define TDIBWIDTHBYTES(bits)	(((bits) + 31) / 32 * 4)

QToupHandler::QToupHandler()
{
	m_hToupcam = nullptr;
	m_pImageData = nullptr;
	//imageSender = new QNetWorkToup;
}


QToupHandler::~QToupHandler()
{
}

bool QToupHandler::openDevice()
{
	for (int i = 10; i > 0; --i)
	{
		m_hToupcam = Toupcam_Open(NULL);
		if (m_hToupcam)
		{
			QThread::msleep(200);
			return true;
		}
	}

	qDebug() << "open deivice Failue";
	return false;
}

void QToupHandler::startDevice()
{
	if (nullptr == m_hToupcam)
	{
		qDebug() << "deivice is not open!";
		return;
	}
	int nWidth = 0, nHeight = 0;
	HRESULT hr = Toupcam_get_Size(m_hToupcam, &nWidth, &nHeight);
	if (FAILED(hr))
		return;
	m_header.iWidth = nWidth;
	m_header.iHeight = nHeight;
	m_header.bSize = TDIBWIDTHBYTES(nWidth * 24) * nHeight;
	if (m_pImageData)
	{
		free(m_pImageData);
		m_pImageData = NULL;
	}
	m_pImageData = malloc(m_header.bSize);
	Toupcam_StartPullModeWithCallback(m_hToupcam,QToupHandler::CamerImageCb,this);
}

void QToupHandler::OnEventImage()
{
	HRESULT hr = Toupcam_PullImage(m_hToupcam, m_pImageData, 24, NULL, NULL);
	unsigned char* im = (unsigned char*)m_pImageData;
	QImage _image((uchar*)m_pImageData, m_header.iWidth, m_header.iHeight, QImage::Format_RGB888);
	int size = _image.byteCount();
	QImage imgSend = _image.scaled(200, 100);
	//static int count = 0;
	//QString str = QString::number(++count);
	//if (count > 9)
	//{
	//	count = 0;
	//}
	//QByteArray _data("@@@");
	//_data.append(str.toLocal8Bit());
	QByteArray _data1((char*)imgSend.bits(), imgSend.byteCount());
	//_data.append(_data1);
	//QByteArray _data2(64000 * 40 - m_header.bSize - 4 - 4, 0);
	//_data.append(_data2);
	//QByteArray _dataTail("####");
	//_data.append(_dataTail);
	//imageSender->sendData(_data1);
}

void QToupHandler::CamerImageCb(unsigned nEvent, void* pCallbackCtx)
{
	QToupHandler* pThis = (QToupHandler*)pCallbackCtx;
	switch (nEvent)
	{
	case TOUPCAM_EVENT_ERROR:
		//OnEventError();
		break;
	case TOUPCAM_EVENT_DISCONNECTED:
		//OnEventDisconnected();
		break;
	case TOUPCAM_EVENT_IMAGE:
		pThis->OnEventImage();
		break;
	case TOUPCAM_EVENT_EXPOSURE:
		//OnEventExpo();
		break;
	case TOUPCAM_EVENT_TEMPTINT:
		//OnEventTempTint();
		break;
	case TOUPCAM_EVENT_STILLIMAGE:
		//OnEventStillImage();
		break;
	default:
		break;
	}
}
